package com.jk11a.shangdaast.notice;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Layout;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jk11a.shangdaast.R;
import com.jk11a.shangdaast.dao.LibraryDao;
import com.jk11a.shangdaast.dao.UserDao;
import com.jk11a.shangdaast.library.Book;
import com.jk11a.shangdaast.library.Library;
import com.jk11a.shangdaast.library.lib_book;
import com.jk11a.shangdaast.library.lib_search;
import com.jk11a.shangdaast.library.lib_user;
import com.jk11a.shangdaast.subject.Subject;
import com.jk11a.shangdaast.user.LogoutActivity;
import com.jk11a.shangdaast.user.UserApplication;
import com.jk11a.shangdaast.user.UserInfoActivity;

public class Notice extends Activity {

	public static Notice instance = null;
	private ViewPager mTabPager;
	private ImageView mTabImg;// 动画图片
	private ImageView mTab1, mTab2, mTab3, mTab4;
	private int zero = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int one;// 单个水平动画位移
	private int two;
	private int three;
	private LinearLayout mClose;
	private LinearLayout mCloseBtn;
	private View layout;
	private View view1;
	private View view2;
	private View view3;
	private View view4; // 4个页卡
	private Button lib_search; // 搜索Button
	private TextView selecttype; // 搜索类型
	private EditText lib_book; // 要搜索的图书
	private PopupWindow popupWindow;// 搜索类型的下拉菜单
	private boolean menu_display = false;
	private PopupWindow menuWindow;
	private LayoutInflater inflater;
	private ImageView notice_iv_homework;
	private ImageView notice_iv_contest;
	private ImageView notice_iv_weekly;
	private ImageView notice_iv_add;

	private Thread popbookThread;
	private String selectString = "类型";
	private static final int MSG_SUCCESS = 0; // 获取热门图书成功
	private static final int MSG_FAILURE = 1; // 获取热门图书失败

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_sda);
		// 启动activity时不自动弹出软键盘
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		instance = this;

		mTabPager = (ViewPager) findViewById(R.id.tabpager);
		mTabPager.setOnPageChangeListener(new MyOnPageChangeListener());

		mTab1 = (ImageView) findViewById(R.id.img_notice);
		mTab2 = (ImageView) findViewById(R.id.img_sub);
		mTab3 = (ImageView) findViewById(R.id.img_lib);
		mTab4 = (ImageView) findViewById(R.id.img_settings);
		mTabImg = (ImageView) findViewById(R.id.img_tab_now);

		mTab1.setOnClickListener(new MyOnClickListener(0));
		mTab2.setOnClickListener(new MyOnClickListener(1));
		mTab3.setOnClickListener(new MyOnClickListener(2));
		mTab4.setOnClickListener(new MyOnClickListener(3));
		Display currDisplay = getWindowManager().getDefaultDisplay();
		int displayWidth = currDisplay.getWidth();
		int displayHeight = currDisplay.getHeight();
		one = displayWidth / 4; // 设置水平动画平移大小
		two = one * 2;
		three = one * 3;

		// 将要分页显示的View装入数组中
		LayoutInflater mLi = LayoutInflater.from(this);
		view1 = mLi.inflate(R.layout.notice, null);
		view2 = mLi.inflate(R.layout.subject, null);
		view3 = mLi.inflate(R.layout.library, null);
		view4 = mLi.inflate(R.layout.setting, null);

		final ArrayList<View> views = new ArrayList<View>();
		views.add(view1);
		views.add(view2);
		views.add(view3);
		views.add(view4);

		// 设置第一页中显示内容
		// 四个view的onclick事件都写在了XML里面 直接调用函数
		// 设置第二页中显示内容
		// 设置第三页中显示内容
		  //设置搜索类型
		selecttype = (TextView) view3.findViewById(R.id.lib_selecttype_tv);
		selecttype.setText(selectString);
		// 新开线程，访问服务器接口获得热门图书并显示出来
		if (popbookThread == null) {
			popbookThread = new Thread(runnable);
			popbookThread.start();
		} else {
			Toast.makeText(getApplication(), "popbook thread 已启动",
					Toast.LENGTH_LONG).show();
		}
		// 搜索图书按钮onclick事件
		lib_search = (Button) view3.findViewById(R.id.lib_lib_btn1);
		lib_book = (EditText) view3.findViewById(R.id.lib_search2_edit);
		lib_search.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) { // 输入所要搜索的书籍信息，

				Intent intent = new Intent();
				intent.setClass(Notice.this, lib_search.class);
				intent.putExtra("bookname", lib_book.getText().toString()); // 把Bundle塞入Intent里面
				startActivity(intent);
			}

		});
		// 设置第四页中显示内容

		PagerAdapter mPagerAdapter = new PagerAdapter() {

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				return arg0 == arg1;
			}

			@Override
			public int getCount() {
				return views.size();
			}

			@Override
			public void destroyItem(View container, int position, Object object) {
				((ViewPager) container).removeView(views.get(position));
			}

			@Override
			public Object instantiateItem(View container, int position) {
				((ViewPager) container).addView(views.get(position));
				return views.get(position);
			}
		};

		mTabPager.setAdapter(mPagerAdapter);
	}

	/**
	 * 头标点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			mTabPager.setCurrentItem(index);
		}
	};

	/*
	 * 页卡切换监听(原作者:D.Winter)
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:
				mTab1.setImageDrawable(getResources().getDrawable(
						R.drawable.tab_notice_pressed));
				if (currIndex == 1) {
					animation = new TranslateAnimation(one, 0, 0, 0);
					mTab2.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_sub_normal));
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, 0, 0, 0);
					mTab3.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_lib_normal));
				} else if (currIndex == 3) {
					animation = new TranslateAnimation(three, 0, 0, 0);
					mTab4.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_settings_normal));
				}
				break;
			case 1:
				mTab2.setImageDrawable(getResources().getDrawable(
						R.drawable.tab_sub_pressed));
				if (currIndex == 0) {
					animation = new TranslateAnimation(zero, one, 0, 0);
					mTab1.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_notice_normal));
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, one, 0, 0);
					mTab3.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_lib_normal));
				} else if (currIndex == 3) {
					animation = new TranslateAnimation(three, one, 0, 0);
					mTab4.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_settings_normal));
				}
				break;
			case 2:
				mTab3.setImageDrawable(getResources().getDrawable(
						R.drawable.tab_lib_pressed));
				if (currIndex == 0) {
					animation = new TranslateAnimation(zero, two, 0, 0);
					mTab1.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_notice_normal));
				} else if (currIndex == 1) {
					animation = new TranslateAnimation(one, two, 0, 0);
					mTab2.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_sub_normal));
				} else if (currIndex == 3) {
					animation = new TranslateAnimation(three, two, 0, 0);
					mTab4.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_settings_normal));
				}
				break;
			case 3:
				mTab4.setImageDrawable(getResources().getDrawable(
						R.drawable.tab_settings_pressed));
				if (currIndex == 0) {
					animation = new TranslateAnimation(zero, three, 0, 0);
					mTab1.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_notice_normal));
				} else if (currIndex == 1) {
					animation = new TranslateAnimation(one, three, 0, 0);
					mTab2.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_sub_normal));
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, three, 0, 0);
					mTab3.setImageDrawable(getResources().getDrawable(
							R.drawable.tab_lib_normal));
				}
				break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(150);
			mTabImg.startAnimation(animation);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitBy2Click(); // 调用双击退出函数
		}
		return false;
	}

	// 双击退出函数
	private static Boolean isExit = false;

	private void exitBy2Click() {
		Timer tExit = null;
		if (isExit == false) {
			isExit = true; // 准备退出
			Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			tExit = new Timer();
			tExit.schedule(new TimerTask() {
				@Override
				public void run() {
					isExit = false; // 取消退出
				}
			}, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
		} else {
			finish();
		}
	}

	// 设置标题栏右侧按钮的作用

	public void homework(View v) {
		Intent intent = new Intent(Notice.this, Homework.class);
		startActivity(intent);
		// Toast.makeText(getApplicationContext(), "登录成功",
		// Toast.LENGTH_LONG).show();
	}

	public void logout(View v) {
		Intent intent = new Intent(Notice.this, LogoutActivity.class);
		startActivity(intent);
		// Toast.makeText(getApplicationContext(), "登录成功",
		// Toast.LENGTH_LONG).show();
	}

	public void userinfo(View v) {
		Intent intent = new Intent(Notice.this, UserInfoActivity.class);
		startActivity(intent);
	}

	public void getmynotice(View v) {
		Intent intent = new Intent(Notice.this, GetMyNotice.class);
		startActivity(intent);
	}

	public void weekly(View v) {
		Intent intent = new Intent(Notice.this, WeeklyNotice.class);
		startActivity(intent);
	}

	public void contest(View v) {
		Intent intent = new Intent(Notice.this, Contest.class);
		startActivity(intent);
	}

	public void addnotice(View v) {
		Intent intent = new Intent(Notice.this, AddNotice.class);
		startActivity(intent);
	}

	public void lib_login(View v) {
		Intent intent = new Intent();
		intent.setClass(Notice.this, lib_user.class);
		startActivity(intent);
	}

	public void lib_selecttype(View v) {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.select_item, new String[] { "书名", "作者", "ISBN/ISSN" });
		ListView listview = new ListView(this);
		listview.setAdapter(adapter);
		popupWindow = new PopupWindow(this);
		popupWindow.setHeight(220);
		popupWindow.setWidth(120);
		popupWindow.setBackgroundDrawable(new ColorDrawable(Color.argb(100, 52,
				53, 55)));
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.setContentView(listview);
		popupWindow.showAsDropDown(selecttype, 0, 0);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				selectString = ((TextView) view).getText().toString();
				selecttype.setText(selectString);
				popupWindow.dismiss();
			}
		});

		if (thread != null && !thread.isAlive()) {
			thread.start();
		}
	}

	Runnable runnable = new Runnable() {
		// 重写run()方法，此方法在新的线程中运行
		@Override
		public void run() {
			// TODO Auto-generated method stub
			LibraryDao libraryDao = new LibraryDao();
			List<Book> books = libraryDao.getPopBook();
			// 获取 成功，向UI线程发送MSG_SUCCESS标识和books对象
			if (books.size() != 0) {
				mHandler.obtainMessage(MSG_SUCCESS, books).sendToTarget();
			} else {
				// 获取 失败，向UI线程发送MSG_FAILURE标识
				mHandler.obtainMessage(MSG_FAILURE).sendToTarget();
				return;
			}
		}
	};
	private Handler mHandler = new Handler() {
		// 重写handleMessage()方法，此方法在UI线程运行
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_SUCCESS:
				Log.i("msg obj", "success");
				List<Book> books = (List<Book>) msg.obj;
				Log.i("msg obj", books.get(0).getBookname() + "!!");
				popbooklist(books);
				Log.i("msg obj", books.get(0).getBookname());
				break;

			case MSG_FAILURE:
				Log.i("msg obj", "failed");
				Toast.makeText(getApplication(), "获取热门图书失败", Toast.LENGTH_LONG)
						.show();
				break;
			}
		}
	};

	// 显示热门图书
	private void popbooklist(List<Book> books) {
		int j = 1;
		int i = 0;
		for (i = 0; i < books.size(); i++) {
			RelativeLayout rLayout = new RelativeLayout(this);
			if (i == 0) {
				rLayout.setBackgroundResource(R.drawable.preference_first_item);
				rLayout.setTop(14);
			} else {
				rLayout.setBackgroundResource(R.drawable.preference_item);
			}
			rLayout.setClickable(true);
			setonclick(this, rLayout, books, i);   //设置每个图书的onclick 事件
			rLayout.setLayoutParams(new RelativeLayout.LayoutParams(
					LayoutParams.FILL_PARENT, 80));

			rLayout.setGravity(Gravity.CENTER);
			TextView tv = new TextView(this);

			tv.setText(books.get(i).getBookname());
			tv.setLayoutParams(new RelativeLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
			tv.setTextColor(Color.rgb(0, 0, 0));
			rLayout.addView(tv);
			((LinearLayout) view3.findViewById(R.id.popbooklist))
					.addView(rLayout);

		}

	}
	public void setonclick(Notice Notice,RelativeLayout rlayout,final List<Book> books,final int i){
		rlayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent =new Intent();
				intent.putExtra("title", books.get(i).getBookname());
				intent.putExtra("publisher", books.get(i).getPublisher());
				intent.putExtra("publishtime", books.get(i).getPublishtime());
				intent.putExtra("writer", books.get(i).getWriter());
				intent.putExtra("bookid", books.get(i).getBookid());
				intent.putExtra("sysnopsis",books.get(i).getSynopsis());
				intent.setClass(Notice.this, lib_book.class);
				startActivity(intent);
			}
		});
	}
	Thread thread = new Thread() {
		public void run() {
			while (true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		};
	};
}
